import axios, { AxiosRequestConfig } from 'axios'
import { ApiRes } from '@/types/data'

import { USER_KEY } from '@/store/modules/user'
import { useStorage } from '@/hooks/useStorage'
import store from '@/store'
import { setInfo } from '@/store/modules/user'
import router from '@/router'

const storage = useStorage()
// const dispatch = useDispatch()
const instance = axios.create({
  baseURL: import.meta.env.VITE_BASEURL
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    const token = storage.getStorage(USER_KEY)?.token
    if (token) {
      config.headers.token = token
    }

    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    if (error.response.status === 401) {
      // token非法，清除token
      store.dispatch(setInfo({}))
      // 跳转到登陆页面
      const location = router.state.location
      console.log(location)

      router.navigate(`/login?redirect=${location.pathname}${location.search}`)
    }

    return Promise.reject(error)
  }
)

export const request = <T>({
  url,
  method = 'GET',
  data
}: AxiosRequestConfig) => {
  return instance<any, ApiRes<T>>({
    url,
    method,
    [method?.toLowerCase() === 'get' ? 'params' : 'data']: data
  })
}
